package final2107.day04;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class BlockingQueueDemo01 {
    public static void main(String[] args) {
        //创建阻塞队列
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
        //创建生产者线程
        Thread productor = new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(1000);
                        int m = (int)(Math.random()*1000);
                        queue.put(m);
                        System.out.println(queue);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };


        //创建任务类对象
        Runnable task = new Runnable() {
            @Override
            public void run() {
                while (true){
                    try{
                        if (queue.size()>=10)
                            System.out.println(Thread.currentThread().getName()+"取出:"+queue.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        //创建消费者线程
        Thread consumer1 = new Thread(task,"线程1");
        Thread consumer2 = new Thread(task,"线程2");

        productor.start();
        consumer1.start();
        consumer2.start();
    }
}
